package com.zlm.design.strategy;

import com.zlm.custom.spring.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zlm
 * @date 2025/5/14
 */
@RestController
public class CustomerController {

    @Autowired
    private List<CustomerService> customerServices;

    @Autowired
    private DefaultCustomerService defaultCustomerService;

    private Map<UserType, CustomerService> customerServiceMap;

    @GetMapping("/customer/{recharge}")
    public String customer(@PathVariable("recharge") int recharge) {
        return customerServices.stream()
                .filter(customerService -> customerService.support(recharge))
                .findFirst()
                .map(CustomerService::findCustomer).get();
    }
    @GetMapping("/customer2/{recharge}")
    public String customer2(@PathVariable("recharge") int recharge) {
        return customerServices.stream()
                .filter(customerService -> customerService.support().equals(UserType.typeOf(recharge)))
                .findFirst()
                .map(CustomerService::findCustomer).get();
    }
    @GetMapping("/customer3/{recharge}")
    public String customer3(@PathVariable("recharge") int recharge) {
        return customerServiceMap
                .getOrDefault(UserType.typeOf(recharge), defaultCustomerService)
                .findCustomer();
    }


    @Autowired
    public void setCustomerServiceMap(List<CustomerService> customerServices) {
        this.customerServiceMap = customerServices.stream()
                .filter(customerService -> customerService.support() != null)
                .collect(Collectors.toMap(CustomerService::findUserTypeFromService, Function.identity()));

        //检测注入的策略数量和用户类型数量是否一致
        if(customerServiceMap.size() != UserType.values().length){
            throw new IllegalStateException("有用户类型没有对应的策略");
        }
    }


}
